package com.ksyun.alert.controller;

import com.ksyun.alert.dto.MetricDTO;
import com.ksyun.alert.dto.MetricQueryReqDTO;
import com.ksyun.alert.dto.MetricQueryRespDTO;
import com.ksyun.alert.result.RestResult;
import com.ksyun.alert.result.Result;
import com.ksyun.alert.service.IMetricService;
import com.ksyun.alert.utils.RequestIdUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.List;

/**
 * 云主机告警接收控制层
 * @author Zhang
 * @date 2024-04-30
 */
@RestController
@RequestMapping("/api/metric")
@Slf4j
@Api(tags = "接收云主机告警controller")
public class MetricController {
    @Resource
    private IMetricService iMetricService;

    /**
     * 接收云主机信息API
     * @param metricList 信息列表
     */
    @ApiOperation(value = "接收云主机信息API")
    @PostMapping("/put")
    public RestResult<Object> putInfo(@RequestBody List<MetricDTO> metricList) {
        String requestId = RequestIdUtil.getRequestId();
        new Thread(() -> {
            RequestIdUtil.generateRequestId(requestId);
            try {
                iMetricService.write2Db(metricList);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }).start();
        return RestResult.success(requestId);
    }

    /**
     * 查询监控数据指标API
     * @param metricQueryReqDTO 查询监控数据指标请求参数
     */
    @ApiOperation(value = "查询监控数据指标API")
    @PostMapping("/query")
    public Result<MetricQueryRespDTO> queryMetricsByPeriodAndReqId(@RequestBody MetricQueryReqDTO metricQueryReqDTO) {
        try {
            return Result.success(iMetricService.queryMetricsByPeriodAndReqId(metricQueryReqDTO));
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }
}
